public class CandidateKey {

	// This method acts as a uniqueness checker for the Candidate object based on the Email__c field
	public static void hasCandidateDuplicates(Candidate__c[] candidates){
		
        //define a map for unique Candidates:
		Map<String,Candidate__c> candidateMap = new Map<String,Candidate__c>();

        for(Candidate__c candidate:candidates) {
        	// ignore candidates with a null email
            if (candidate.email__c != null){
	        	String lastName = candidate.Last_Name__c.toLowerCase();
	        	String email = candidate.Email__c.toLowerCase();
	        	String uKey = lastName + email;       	        	
             
            	//look for dupes within the batch
				if(candidateMap.containsKey(uKey)) candidate.addError('Duplicate LastName + Email found in batch'); 
				else candidateMap.put(uKey, candidate);      
            }
		}
  		//now hit the DB looking for dupes
  		if (!candidateMap.isEmpty()){
	  		for(Candidate__c[] candidatesCheck:[select Id, unique_key__c from Candidate__c where unique_key__c IN :candidateMap.keySet()]) {
				for(Candidate__c candidate:candidatesCheck) {
	  				String currentCandidateId = candidate.Id;
	  				//if there's a dupe and this isn't the current record, then add the error.
	  				if(candidateMap.containsKey(candidate.unique_key__c) && (currentCandidateId != candidateMap.get(candidate.unique_key__c).Id)) {
	     				candidateMap.get(candidate.unique_key__c).addError('Duplicate LastName + Email found in salesforce(id: ' + candidate.id + ')');
	  				}
	  			}
	    	}
  		}
  	} // end hasCandidateDuplicates
}